package com.wrupple.muba.rest.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.wrupple.muba.common.shared.StateTransition;

/**
 * An implementation of the asynccallback interface designed to ease
 * implementation.
 * 
 * on success if executes a data call back with the retrived results, on failure
 * it logs the error, and optionally displays a message to the user
 * 
 * @author japi
 * 
 * @param <T>
 */
public class AsyncCallbackImpl<T> implements AsyncCallback<T> {
	private StateTransition<T> callback;
	private String AppMessage;
	private String userMesage;

	/**
	 * creates a new instance of this callback type
	 * 
	 * @param callback
	 *            executed when results are retrived
	 * @param clazz
	 *            the class of the calling object, used to log the error in case
	 *            something goes wrong
	 * @param appMessage
	 *            the internal log message if an exception is thrown
	 * @param userMesage
	 *            the user message displayed if something goes wrong
	 */

	public AsyncCallbackImpl(StateTransition<T> callback, String logMessage, String userErrorMesage, String waitMessage) {
		super();
		this.callback = callback;
		AppMessage = logMessage;
		this.userMesage = userErrorMesage;
		//StaticDesktopAccess.setApplicationOnStandby(waitMessage);
	}

	public AsyncCallbackImpl(StateTransition<T> callback, String logMessage, String userErrorMesage) {
		this.callback = callback;
		AppMessage = logMessage;
		this.userMesage = userErrorMesage;
		//StaticDesktopAccess.setApplicationOnStandby("Getting information from the server.");
	}

	@Override
	public void onFailure(Throwable e) {
		//StaticDesktopAccess.dismissApplicationStandby();
		GWT.log(AppMessage, e);
		if (userMesage != null) {
			//StaticDesktopAccess.addUIError(userMesage);
		}
	}

	@Override
	public void onSuccess(T result) {
		//FIXME StaticDesktopAccess.dismissApplicationStandby();
		callback.setResult(result);
		callback.execute();
	}

}
